package top.didi.study.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import top.didi.study.base.PageBean;
import top.didi.study.base.R;
import top.didi.study.dao.TbCpuDAO;
import top.didi.study.entity.TbCpu;
import top.didi.study.service.TbCpuService;
import top.didi.study.vo.PageVO;

@Service
@Slf4j
@RequiredArgsConstructor
public class TbCpuServiceImpl implements TbCpuService {
    private final TbCpuDAO tbCpuDAO;

    private TbCpu queryByCpu(String cpu) {
        QueryWrapper<TbCpu> wrapper = new QueryWrapper<>();
        wrapper.eq("cpu", cpu);
        TbCpu tbCpu = tbCpuDAO.selectOne(wrapper);
        return tbCpu;
    }

    @Override
    public R<String> insert(TbCpu tbCpu) {

        TbCpu check = queryByCpu(tbCpu.getCpu());
        if (check != null) {
            return R.fail("该CPU已存在", null);
        }

        int i = tbCpuDAO.insert(tbCpu);
        return i == 1 ? R.ok("添加成功", null) : R.fail("添加失败", null);
    }

    @Override
    public R<String> update(TbCpu tbCpu) {

        TbCpu check = queryByCpu(tbCpu.getCpu());
        if (check != null && !check.getId().equals(tbCpu.getId())) {
            return R.fail("该CPU已存在", null);
        }

        int i = tbCpuDAO.updateById(tbCpu);
        return i == 1 ? R.ok("修改成功", null) : R.fail("修改失败", null);
    }

    @Override
    public R<String> delete(Integer id) {
        int i = tbCpuDAO.deleteById(id);
        return i == 1 ? R.ok("删除成功", null) : R.fail("删除失败", null);
    }

    @Override
    public R<TbCpu> queryById(Integer id) {
        TbCpu tbCpu = tbCpuDAO.selectById(id);
        return tbCpu == null ? R.fail("查询失败", null) : R.ok(tbCpu);
    }

    @Override
    public R<PageVO<TbCpu>> queryPage(PageBean pageBean, TbCpu tbCpu) {
        IPage<TbCpu> page = new Page<>(pageBean.getPageNumber(),pageBean.getPageSize());
        QueryWrapper<TbCpu> wrapper = new QueryWrapper<>();
        wrapper.like(
                StringUtils.hasText(tbCpu.getCpu()),
                "cpu",
                tbCpu.getCpu()
        );
        wrapper.like(
                StringUtils.hasText(tbCpu.getManufacturer()),
                "manufacturer",
                tbCpu.getManufacturer()
        );
        page = tbCpuDAO.selectPage(page,wrapper);
        return R.ok(page);
    }

}
